<template>
    <el-select
        :ref="(el) => selectRef = el"
        filterable
        collapse-tags
        v-model="state"
        class="width_100"
        :disabled="disabled"
        :multiple="multiple"
        collapse-tags-tooltip
        :clearable="clearable"
        :placeholder="placeholder"
        :filter-method="querySearch"
        @change="change"
        @focus="focus"
    >
      <el-option  v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
</template>

<script setup lang="ts">

/**
 * @props
 */

const props = defineProps({
    // 值
    value: {
        type: String,
        default: ''
    },
    // 筛选
    options: {
        type: Array,
        default: []
    } as any,
    // 多选
    multiple: {
        type: Boolean,
        default: false,
    },
    // 清除
    clearable: {
        type: Boolean,
        default: true,
    },
    // 禁用
    disabled: {
        type: Boolean,
        default: false,
    },
    placeholder: {
        type: String,
        default: '请选择'
    }
})

/**
 * @var
 */

const state = toRef(props.value)
const optionsList = toRef<any>(props.options)
const selectRef = ref()
/**
 * @method
 */
const emit = defineEmits(['change', 'focus'])

// 全模糊
const querySearch = (value: any) => {
    optionsList.value = props.options.filter((option: any) => {
        return (option?.label ?? '')?.toLowerCase().includes(value?.trim().toLowerCase())
    })
}

// 左模糊
const querySearch1 = (queryString: string) => {
    const results = queryString
        ? props.options.filter(createFilter(queryString))
        : props.options
    optionsList.value = results
}
const createFilter = (queryString: any) => {
    return (restaurant: any) => {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// change事件
const change = (value: any) => {
    emit('change', value)
}
//focus事件
const focus = (value: any) => {
    emit('focus')
}

watch(
    () => props.options,
    (newValue, oldValue) => {
        optionsList.value = newValue
    },
    { deep: true }
)
watch(
    () => props.value,
    (newValue, oldValue) => {
        state.value = newValue
    },
    { deep: true, immediate: true }
)

defineExpose({
    selectRef
})

</script>

<style scoped></style>
